package cn.xorange.commons.security.filter.handler;

import cn.xorange.commons.security.constants.HeaderConstants;
import cn.xorange.commons.security.constants.SecurityConstants;
import cn.xorange.commons.security.entity.SecurityTenant;
import cn.xorange.commons.security.exception.SecurityErrorCode;
import cn.xorange.commons.security.filter.FilterHandler;
import cn.xorange.commons.security.filter.LoginFilterService;
import cn.xorange.commons.security.mapper.LoginTenantMapper;
import cn.xorange.commons.security.service.LoginHandler;
import cn.xorange.commons.security.service.LoginHandlerFactory;
import cn.xorange.commons.utils.captcha.Captcha;
import cn.xorange.commons.utils.captcha.CaptchaService;
import cn.xorange.commons.utils.http.ServletUtils;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.List;
import java.util.Objects;

/**
 * @author : yangjian
 * @date : 2023/12/25
 */

// 若未配置havingValue的值，matchIfMissing为true则无论是否有配置都会加载配置类，matchIfMissing为false，有配置加载类，无配置不加载类。
@ConditionalOnProperty(prefix = "spring.security" ,name = "enable-tenant",havingValue = "true", matchIfMissing=false)
public class TenantFilterHandler implements FilterHandler {

    @Resource
    LoginTenantMapper tenantMapper;
    @Resource
    LoginFilterService filterService;
    @Resource
    LoginHandlerFactory loginHandlerFactory;
    @Resource
    LoginFilterService loginFilterService;
    @Resource
    CaptchaService captchaService;


    @Override
    public String url() {
        return SecurityConstants.URL_GET_TENANT;
    }

    @Override
    public Boolean passToken() {
        return true;
    }

    @Override
    public void handler(HttpServletRequest request, HttpServletResponse response) {
        // 带租户地址登录的情况下 通过地址获取shortname
        JSONObject object = ServletUtils.getParamJsonObj(request);
        String sysType = request.getHeader(HeaderConstants.X_SYS_TYPE);
        String loginName = object.getString(SecurityConstants.LOGIN_NAME);
        String loginType = object.getString(SecurityConstants.LOGIN_TYPE);
        String tenantId = object.getString(SecurityConstants.USER_TENANT_ID);
        LoginHandler loginHandler = this.loginFilterService.getLoginHandler(sysType,loginType,loginHandlerFactory);
        boolean enableCaptcha = this.loginFilterService.enableCaptcha(loginHandler);
        if(enableCaptcha){
            String code = object.getString(SecurityConstants.LOGIN_CODE);
            String uuid = object.getString(SecurityConstants.LOGIN_UUID);
            Captcha captcha = captchaService.checkCaptcha(uuid,code);
            if(!SecurityConstants.FLAG_SUCCESS.equals(String.valueOf(captcha.getSysCode()))){
                ServletUtils.responseOut(response, captcha.getStatus(), captcha.getSysCode(),captcha.getMsg(),null);
                return;
            }
        }

        if(Objects.nonNull(tenantId) && !tenantId.isEmpty()){
            ServletUtils.responseSuccessOut(response, tenantId);
        }else {
            String superUser = filterService.checkSuperUserLogin(loginName);
            List<SecurityTenant> lst;
            if(SecurityConstants.FLAG_YES.equals(superUser)){
                lst = this.tenantMapper.selectTenantListByAdmin();
            }else {
                lst = this.tenantMapper.selectUserListByLoginName(loginName);
            }
            if(lst.isEmpty()){
                SecurityErrorCode errorCode = SecurityErrorCode.TENANT_NOT_FOUND_EXCEPTION;
                ServletUtils.responseOut(response,errorCode.getStatus(),errorCode.getCode(),errorCode.getMsg(),null);
            }else if(lst.size()==1){
                ServletUtils.responseSuccessOut(response, lst.get(0).getTenantId());
            }else {
                ServletUtils.responseSuccessOut(response, (Serializable) lst);
            }
        }


    }
}
